# 第 6 章 字典
# 6.1 一个简单的字典
allen = {'color': 'green', 'age': 5}
print(allen['color'])
print(allen['age'])
# 6.2 使用字典
# 6.2.1 访问字典中的值
allen = {'color': 'green', 'age': 5}
print(allen['color'])
age = allen['age']
print("age "+str(age))

# 6.2.2 添加键—值对
allen = {'color': 'green', 'age': 5}
print(allen)
print(allen['color'])
allen['x'] = 10
allen['y'] = 20
print(allen)

# 6.2.3 先创建一个空字典
allen0 = {}
allen['color'] = 'green'
print(allen)

# 6.2.4 修改字典中的值
allen1 = {'color': 'green', 'age': 5}
allen['color'] = 'blue'
print(allen)

# 6.2.5 删除键—值对
allen1 = {'color': 'green', 'age': 5}
print(allen1)
del allen1['age']
print(allen1)

# 6.2.6 由类似对象组成的字典
favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
print(favorite_languages['sarah'])

# 6.3 遍历字典
allen = {'color': 'green', 'color2': 'red'}
for k, v in allen.items():
    print("key" + k)
    print("value" + v)
users = {'zzp': '软件', 'xm': '销售'}
for name,zy in users.items():
    print("姓名:"+name)
    print("职业:"+zy)

# 6.3.2 遍历字典中的所有键
users = {'zzp': '软件', 'xm': '销售','gys':'软件'}
for name in users.keys():
    print(name)

# 6.3.3 按顺序遍历字典中的所有键
for name in sorted(users.keys()):
    print(name)

# 6.3.4 遍历字典中的所有值
for zy in users.values():
    print(zy)
for zy in set(users.values()):
    print(zy)

# 6.4 嵌套
# 6.4.1 字典列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)

aliens = []
for alien_number in range(30):
    new_aliens = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_aliens)
print(aliens)


alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
print(aliens)
for alien in aliens:
    if alien['color'] == 'green':
        alien['color'] ='blue'
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
print(aliens)
print("修改了")

# 6.4.2 在字典中存储列表
shuma={'shouji': 'ios','diannao': ['windows', 'linux']}
print(shuma)
for top in shuma['diannao']:
    print(top)

# 6.4.3 在字典中存储字典
users = {
    'new_aliens1': {
        'color': 'green',
        'points': 5,
        'speed': 'slow'
    },
    'new_aliens2': {
        'color': 'green',
        'points': 5,
        'speed': 'slow'
    }
}
for username, user_info in users.items():
    print(username)
    print(user_info['color']+" "+user_info['speed'])

